package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.json.JSONArray
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wisdge.dataservice.Result;
import cn.com.elite.Util;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

/**
 *
 * @Title: autoDECaseReqReturn
 * @Description: DE30013 市平台市属责任单位申请回退 市平台市属责任单位申请回退
 * @author: LiJuntao
 * @date 2020-05-15 下午1:18:32
 *
 */
public class autoDECaseReqReturn implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoDECaseReqReturn.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        String logPrefix = "DE30013 市平台市属责任单位申请回退-";

        //初始化执行耗时信息
        long rstartTime = System.currentTimeMillis();
        long rendTime = System.currentTimeMillis();
        log.debug(logPrefix + "开始...时间:" + rstartTime);

        //初始化同步结果
        String errorCode = "";
        String errorMsg = "";
        int syncFlag = 0;

        //查询待同步数字化城管的反馈结果案件
        String syncTaskSQL = "select rec_Id,evtId,returnDescribe,reqDate,reqUserName,reqUserDeptName,activityInstId,fromId from SZWG_DE_Case_ReqReturn where syncFlag = 0 and createTime > DATEADD(day, -7, GETDATE()) and syncTimes < syncLimit";
        List syncTaskList = eliteBean.chaxun_sql(syncTaskSQL, "dataSource");
        log.debug(logPrefix + "获取数据SQL:" + syncTaskSQL + " 数量:" + syncTaskList.size());

        if (syncTaskList.size() > 0) {
            for (int i = 0; i < syncTaskList.size(); i++) {
                String requestId = "SW-" + KHUtil.getRandomString(29).toUpperCase();
                String time = String.valueOf(System.currentTimeMillis());

                // 设置头文件
                Map<String, String> headMap = new HashMap<String, String>();
                headMap.put("Content-Type", "application/json");
                headMap.put("funCode", "DE30013");
                headMap.put("appId", getProperty.get("DE.appId"));
                headMap.put("appKey", getProperty.get("DE.appKey"));
                headMap.put("requestId", requestId);
                headMap.put("timestamp", time);
                headMap.put("encoding", "");

                String attachListSQL = "select attachType, attachFilePath, attachFileName from SZWG_DE_Case_ReqAttachs where attachStatus = 0 and rec_Id = '" + syncTaskList.get(i).get("rec_Id") + "'"
                List<Map<String, Object>> getAttachList = eliteBean.chaxun_sql(attachListSQL, "dataSource");
                log.debug(logPrefix + "getAttachListSQL获取数据结果:" + getAttachList + " 数量:" + getAttachList.size());

                //定义附件对象
                JSONArray callArray = new JSONArray();
                for (int j = 0; j < getAttachList.size(); j++) {
                    JSONObject attachListJson = new JSONObject();
                    Map<String, Object> reMap = getAttachList.get(j);

                    String attachType = reMap.get("attachType").toString();
                    String attachFilePath = reMap.get("attachFilePath").toString();
                    String attachFileName = reMap.get("attachFileName").toString();

                    attachListJson.put("attachType", attachType);
                    attachListJson.put("attachFilePath", attachFilePath);
                    attachListJson.put("attachFileName", attachFileName);

                    callArray.put(attachListJson);
                }

                //定义调用报文
                JSONObject callJson = new JSONObject();

                callJson.put("evtId", syncTaskList.get(i).get("evtId"));
                callJson.put("returnDescribe", syncTaskList.get(i).get("returnDescribe"));
                callJson.put("reqDate", syncTaskList.get(i).get("reqDate"));
                callJson.put("reqUserName", syncTaskList.get(i).get("reqUserName"));
                callJson.put("reqUserDeptName", syncTaskList.get(i).get("reqUserDeptName"));
                callJson.put("activityInstId", syncTaskList.get(i).get("activityInstId"));
                callJson.put("umEvtAttachList", callArray);
                callJson.put("fromId", syncTaskList.get(i).get("fromId"));

                //调用数字化城管接口
                try {
                    log.debug(logPrefix + "调用地址URL：" + getProperty.get("DE.URL") + "调用发送报文信息：" + callJson.toString());
                    String reJson = Util.doHttpPostUseHead(getProperty.get("DE.URL"), callJson.toString(), "UTF-8", 10000, 0, headMap);
                    log.debug(logPrefix + "调用返回信息：" + reJson);

                    JSONObject inObject = new JSONObject(reJson);
                    errorCode = KHUtil.GetJV(inObject, "errorCode");
                    errorMsg = KHUtil.GetJV(inObject, "errorMsg");
                    log.debug(logPrefix + "解析返回信息errorCode：" + errorCode + "解析返回信息errorMsg：" + errorMsg);
                    syncFlag = 1;

                    if (errorCode.equals("0")) {
                        errorMsg = "交易成功";
                    }
                } catch (Exception e) {
                    log.error(logPrefix + "调用数字化城管接口错误:" + e.getMessage());
                    errorCode = "";
                    syncFlag = 0;
                }

                def updateCaseReqComSQL1 = eliteBean.update("Update SZWG_DE_Case_ReqReturn Set syncFlag = '" + syncFlag + "', syncLastTime = getdate(),syncTimes = syncTimes + 1 WHERE rec_Id = '" + syncTaskList.get(i).get("rec_Id") + "'", "dataSource");
                log.debug(logPrefix + "SQL更新数据(将调用次数累加):" + updateCaseReqComSQL1);

                //为避免对方失败返回信息异常导致插入失败所以与次数更新分开
                def updateCaseReqComSQL2 = eliteBean.update("Update SZWG_DE_Case_ReqReturn Set errorCode = '" + errorCode + "',errorMsg = '" + errorMsg + "' WHERE rec_Id = '" + syncTaskList.get(i).get("rec_Id") + "'", "dataSource");
                log.debug(logPrefix + "SQL更新数据(记录调用结果):" + updateCaseReqComSQL2);
            }

            rendTime = System.currentTimeMillis();
            log.debug(logPrefix + "结束..." + " 处理时长(毫秒):" + (rendTime - rstartTime));

        } else {
            rendTime = System.currentTimeMillis();
            log.debug(logPrefix + "无任务-结束..." + " 处理时长(毫秒):" + (rendTime - rstartTime));
        }

    }
}